from . import news_blueprint
from ..utils.response_util import *
from ..utils.exception import APIException
from ..utils.error_code import *
from ..models import db, Question, News, Homework, QuestionAnswer
from ..utils.check import *

from flask import request, url_for
from math import ceil


@news_blueprint.route("/", methods=["GET", "POST"])
def main():
    return "News"


@news_blueprint.errorhandler(APIException)
def error(e):
    return APIException.to_dict(e)


@news_blueprint.route("/list", methods=["GET"])
def news_get():
    """
    查询 news 列表(返回三个 news)
    :return:
    """
    r = list()
    newses = News.query.order_by(-News.create_time).all()
    if newses is None:
        raise APIException(NO_NEWS_EXISTS)

    newses = newses[: 3]
    for news in newses:
        tmp = dict()
        tmp["id"] = news.news_id
        tmp["title"] = news.news_title
        tmp["time"] = str(news.create_time)
        r.append(tmp)

    return response(200, "Query News List Success", r)


@news_blueprint.route("/add", methods=["POST"])
@user_is_login
@check_user_type_2
def news_add():
    """
    添加 news
    :return:
    """
    data = get_data()
    news_title = data.get("newsTitle")
    news_content = data.get("newsContent")
    username = session.get("username")

    news = News(news_title, news_content, username)

    try:
        db.session.add(news)
        db.session.commit()
    except:
        db.session.rollback()
        raise APIException(ADD_ERROR)

    return response(200, "Add News Success", {})


@news_blueprint.route("/search", methods=["GET"])
def news_search():
    """
    查看 news
    :return:
    """
    data = request.args
    news_id = data.get("newsId")
    r = dict()

    news = News.query.filter(News.news_id == news_id).first()
    if news is None:
        raise APIException(NO_NEWS_EXISTS)
    r["newsId"] = news.news_id
    r["newsTitle"] = news.news_title
    r["newsContent"] = news.news_content
    r["newsCreateTime"] = str(news.create_time)

    return response(200, "Search News Success", r)


@news_blueprint.route("/all", methods=["GET", "POST"])
def news_get_all():
    """
    获取所有 news
    :return:
    """
    data = request.args
    try:
        current_page = int(data.get("currentPage"))
    except:
        current_page = 1
    data_per_page = 10

    newses = News.query.order_by(-News.create_time).all()
    if newses is None:
        raise APIException(NO_NEWS_EXISTS)
    r = list()
    news_len = len(newses)
    max_page_num = ceil(news_len / data_per_page)

    for news in newses:
        tmp = dict()
        tmp["id"] = news.news_id
        tmp["title"] = news.news_title
        tmp["newsAddUser"] = news.news_add_user_id
        tmp["newsCreateTime"] = str(news.create_time)
        r.append(tmp)

    ret = {
        "currentPage": current_page,
        "maxPageNum": max_page_num,
        "num": news_len,
        "list": r[data_per_page * (current_page - 1): data_per_page * current_page]
    }

    return response(200, "Query News List Success", ret)


@news_blueprint.route("/update", methods=["POST"])
@check_user_type_2
def news_update():
    """
    修改 news
    :return:
    """
    data = get_data()
    news_id = data.get("newsId")
    news_title = data.get("newsTitle")
    news_content = data.get("newsContent")
    new_data = {}

    if news_id is None:
        raise APIException(NO_DATA_FOUND)
    news = News.query.filter_by(news_id=news_id).first()
    if news is None:
        raise APIException(NO_NEWS_EXISTS)

    if news_title is not None:
        new_data["news_title"] = news_title
    if news_content is not None:
        new_data["news_content"] = news_content
    new_data["create_time"] = get_time()

    res = News.query.filter_by(news_id=news_id).update(new_data)
    try:
        db.session.commit()
        db.session.close()
    except:
        db.session.rollback()
        raise APIException(UPDATE_ERROR)

    if res == 1:
        return response(200, "Update News Success", new_data)
    else:
        raise APIException(UPDATE_ERROR)


@news_blueprint.route("/delete", methods=["POST"])
@user_is_login
@check_user_type_2
def news_delete():
    """
    删除 news
    :return:
    """
    data = get_data()
    news_id = data.get("newsId")

    res = News.query.filter_by(news_id=news_id).delete()
    try:
        db.session.commit()
        db.session.close()
    except:
        db.session.rollback()
        db.session.close()

    if res == 1:
        return response(200, "Delete News Success", {"newsId": news_id})
    else:
        raise APIException(DELETE_ERROR)
